#include "MephistoCAM.h"

int init_adc2reg_clk_config( ADC2REG_CLK_CONFIG *cfg ){

    cfg->reg_num        = 1;
    cfg->reg_cnt_max    = 78;   // 39MHz/78/2 = 0.25MHz

    return 0;
}

int read_adc2reg_clk_config( ADC2REG_CLK_CONFIG *cfg, char *inifile, char *section ){
    
    dictionary *ini = iniparser_load( inifile );

    cfg->reg_num        = 1;
    
    int reg_cnt_max_tmp = cfg->reg_cnt_max;

    char sec_param[64];
    sprintf(sec_param, "%s:CLK_REG_CNT_MAX", section);
    cfg->reg_cnt_max    = (uint32_t)iniparser_getint(ini, sec_param, reg_cnt_max_tmp );

/*    if( cfg->reg_cnt_max > 127 ){*/
/*        printf("> (adc2reg_clk) cfg->reg_cnt_max MUST be less or equal to 127!!!\n");*/
/*        exit(0);*/
/*    }*/

    iniparser_freedict( ini );

    return 0;
}

int free_adc2reg_clk_config( ADC2REG_CLK_CONFIG *cfg ){

    printf("> (free_adc2reg_clk_config) do nothing ...\n");

    return 0;
}

int config_adc2reg_clk_via_SPI( uint32_t *gpio_reg,
                                uint32_t *gpio2_reg, 
                                ADC2REG_CLK_CONFIG *cfg ){

    clrbit(*gpio_reg, BIT_156MHz_EN);	// 停止156MHz晶振的输出
    usleep(1000);

    SPI_PS_SEND_DATA( gpio_reg,
                      gpio2_reg,
                      &(cfg->reg_cnt_max),
                      1,
                      SPI_PS_ADC2REG_CLK );

    int sclk_cnt = 5;
    while( sclk_cnt>0 ){
        SPI_PS_SCLK(gpio_reg);
        sclk_cnt--;
    }

    usleep(1000);
    setbit(*gpio_reg, BIT_156MHz_EN);	// 恢复156MHz晶振的输出

    return 0;
}
